package com.vv.tools.modules.auth.handler;

import com.vv.tools.common.message.Result;
import com.vv.tools.common.message.ResultEnum;
import com.vv.tools.common.util.ResponseUtil;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

/**
 * @author wen.li
 * 身份校验失败
 * 用于处理身份验证失败的情况
 */
@Component("loginFiledHandler")
public class LoginFiledHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
        ResultEnum re;
        if (exception instanceof AccountExpiredException) {
            re = ResultEnum.AUTH_ACCOUNT_EXPIRED;
        } else if (exception instanceof BadCredentialsException) {
            re = ResultEnum.AUTH_BAD_CREDENTIALS;
        } else if (exception instanceof CredentialsExpiredException) {
            re = ResultEnum.AUTH_CREDENTIALS_EXPIRED;
        } else if (exception instanceof DisabledException) {
            re = ResultEnum.AUTH_DISABLED;
        } else if (exception instanceof LockedException) {
            re = ResultEnum.AUTH_LOCKED;
        } else if (exception instanceof UsernameNotFoundException) {
            re = ResultEnum.AUTH_USERNAME_NOT_FOUND;
        } else if (exception instanceof InternalAuthenticationServiceException) {
            re = ResultEnum.AUTH_INTERNAL_AUTHENTICATION_SERVICE;
        } else {
            re = ResultEnum.EXCEPTION;
        }
        ResponseUtil.of(response, Result.fail(re));
    }

}
